package com.zy.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.zy.pro.utils.BaseConst;
import com.zy.pro.utils.Constant;

public class UploadHelper {

	private static String imageUpload = Constant.DECOR_IMAGE_UPLOAD_PATH;
	
	/**
	 * 上传图片
	 * @param upload
	 * @param oldImageUrl 
	 * @param logger
	 * @return 上传图片路径
	 * @throws IOException
	 */
	public static String upload(MultipartFile upload, String separateName, HttpServletRequest request, Logger logger) throws IOException {
		String imageUrl = "";
		if (ImageTypeUtil.isImage(upload.getOriginalFilename()) && upload.getSize() <= BaseConst.UPLOAD_IMAGE_MAX) {
			String fileName = upload.getOriginalFilename();
//			Integer houseId = SessionUtils.getRole(request).getHouseId();
			String houseId = "";
			logger.info("[" + houseId + "/" + separateName + "]上传图片名称==>>" + fileName);
			
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");
			String path = "/" + houseId + "/" + separateName + "/" + dateformat.format(new Date());
			String galleryRealDir = imageUpload + path;
			File gallerySaveDir = new File(galleryRealDir);
			if (!gallerySaveDir.exists()){
				gallerySaveDir.mkdirs();// 如果目录不存在就创建
			}
			
			String ext = fileName.substring(fileName.lastIndexOf('.'));
			String imageName = UUIDHelper.getUUID36() + ext;// 构建文件名称
			byte[] bytes = upload.getBytes();
			File uploadedFile = new File(gallerySaveDir, imageName);
			FileCopyUtils.copy(bytes, uploadedFile);

			imageUrl = path + "/" + imageName;
			logger.info("[" + houseId + "/" + separateName + "]上传图片路径==>>" + imageUrl);
		}
		return imageUrl;
	}
	
	/**
	* 复制单个文件
	* @param oldPath String 原文件路径 如：c:/fqf.txt
	* @param newPath String 复制后路径 如：f:/fqf.txt
	* @return boolean
	*/
	public static void copyFile(String oldPath, String newPath, String separateName, HttpServletRequest request, Logger logger) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(imageUpload + oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(imageUpload + oldPath); // 读入原文件
				String[] s = newPath.split("/");
				String newFilePath = "";
				for (int i = 0; i < s.length - 1; i++) {
					newFilePath += "/" + s[i];
				}
				File gallerySaveDir = new File(imageUpload + newFilePath);
				if (!gallerySaveDir.exists()){
					gallerySaveDir.mkdirs();// 如果目录不存在就创建
				}
				FileOutputStream fs = new FileOutputStream(imageUpload + newPath);
				byte[] buffer = new byte[1444];
				int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					// System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
			//判断是否需要删除原有图片
			if(separateName != null && !"".equals(separateName)){
				deletePic(oldPath,separateName,request,logger);
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();
		}
	}

	/**
	 * 删除原来图片
	 * @param url
	 * @param logger
	 */
	public static void deletePic(String oldImageUrl, String separateName, HttpServletRequest request, Logger logger){
		//删除原来上传的图片
		if(oldImageUrl != null && !"".equals(oldImageUrl)){
//			Integer houseId = SessionUtils.getRole(request).getHouseId();
			String houseId = "";
			String imageUrl = imageUpload + oldImageUrl;
			File oldFile = new File(imageUrl);
			if(oldFile.exists()){
				oldFile.delete();
				logger.info("[" + houseId + "/" + separateName + "]删除原来图片==>>" + imageUrl);
			}
		}
	}
}
